/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.maze.behaviours;

import java.util.ArrayList;
import org.maze.Maze;
import org.maze.individual.Individual;

/**
 *
 * @author Thomas
 */
public class ChangeLastImprovementBehaviour extends AbstractImprovementBehaviour implements IImprovementBehaviour{

    public byte[] improve(Individual individual) {
        ArrayList<Integer> path = individual.getPath();
        if(path.isEmpty() || path.size() < 2){
            return individual.getGenome();
        }
        int wrongPosition = path.size();
        byte[] genome = individual.getGenome();
        int pos = path.get(path.size()-1);
        int x = pos%Maze.SIZE;
        int y = pos/Maze.SIZE;
        Maze maze = Maze.getInstance();
        int dir=0;
        boolean isInside=false;
        int count = 0;
        do{
            dir = rand.nextInt(4);
            if(dir == Individual.EAST){
                x=+1;
            }else if(dir == Individual.WEST){
                x=-1;
            }else if(dir == Individual.NORTH){
                y-=1;
            }else if(dir == Individual.SOUTH){
                y+=1;
            }
            isInside=true;
            if(x<0 && x>=Maze.SIZE)
                isInside=false;
            if(y<0 && y>=Maze.SIZE)
                isInside=false;
            // we can't find a solution we exit
            if(count++ > 15)
                return individual.getGenome();
        }while(!isInside || maze.getGridValue(x, y)==Maze.WALL_FIELD || path.get(path.size()-2) == x+y*Maze.SIZE);
        // is not inside the maze || go through a wall || go back to the previous cases
        genome[wrongPosition] = (byte)dir;
        return genome;
    }
}
